package cn.wolfcode.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class OssUtils {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    public String upLoad(MultipartFile image) throws IOException {
        InputStream inputStream = image.getInputStream();
        String originalFilename = image.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        OSS build = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        build.putObject(bucketName, newFileName, inputStream);
        return new StringBuffer(endpoint).insert(8, bucketName+".").append("/").append(newFileName).toString();
    }
}
